/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.nanosl.norg.general.gui;

import com.nanosl.lib.db.Manager;
import com.nanosl.norg.ent.City;
import com.nanosl.norg.util.NTopComponent;
import java.awt.Color;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.util.Collection;
import java.util.Iterator;
import javax.swing.table.DefaultTableModel;
import org.netbeans.api.settings.ConvertAsProperties;
import org.netbeans.spi.actions.AbstractSavable;
import org.openide.DialogDisplayer;
import org.openide.NotifyDescriptor;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.UndoRedo;
import org.openide.util.Exceptions;
import org.openide.util.NbBundle.Messages;
import org.openide.util.lookup.AbstractLookup;
import org.openide.util.lookup.InstanceContent;
import org.openide.windows.TopComponent;
import org.openide.windows.WindowManager;

/**
 * Top component which displays something.
 */
@ConvertAsProperties(
    dtd = "-//com.nanosl.credit.editor//CityEditor//EN",
autostore = false)
@TopComponent.Description(
    preferredID = "CityEditorTopComponent",
//iconBase="SET/PATH/TO/ICON/HERE", 
persistenceType = TopComponent.PERSISTENCE_ALWAYS)
@TopComponent.Registration(mode = "editor", openAtStartup = false)
@ActionID(category = "Window", id = "com.nanosl.credit.editor.CityEditorTopComponent")
@ActionReference(path = "Menu/Editor", position = 6)
@TopComponent.OpenActionRegistration(
    displayName = "#CTL_CityEditorAction",
preferredID = "CityEditorTopComponent")
@Messages({
    "CTL_CityEditorAction=CityEditor",
    "CTL_CityEditorTopComponent=CityEditor Window",
    "HINT_CityEditorTopComponent=This is a CityEditor window"
})
public final class CityEditorTopComponent extends NTopComponent{

//    Manager mananger = Manager.getInstance();
    DefaultTableModel cityTableModel = new DefaultTableModel();

    public CityEditorTopComponent() {
        initComponents();
        cityTableModel = (DefaultTableModel) cityTable.getModel();
        resetFields();
        setName(Bundle.CTL_CityEditorTopComponent());
        setToolTipText(Bundle.HINT_CityEditorTopComponent());

        instanceContent = new InstanceContent();
        associateLookup(new AbstractLookup(instanceContent));
        cityTextField.getDocument().addUndoableEditListener(UndoRedoManager);
        cityTextField.addKeyListener(new KeyAdapter() {
            @Override
            public void keyReleased(KeyEvent e) {
                modify();
            }
        });
    }

    private void modify() {
        if (getLookup().lookup(CitySavable.class) == null) {
            instanceContent.add(new CitySavable());
        }
    }

    private void fillCityTable() {
        cityTableModel.setRowCount(0);
        Collection<City> codeCollection = manager.find(City.class);
        for (Iterator<City> it = codeCollection.iterator(); it.hasNext();) {
            City city = it.next();
            Object[] row = {
                city};
            cityTableModel.addRow(row);
        }
    }

    public static void display() {
        CityEditorTopComponent tc = (CityEditorTopComponent) WindowManager.getDefault().findTopComponent("CityEditorTopComponent");
        tc.open();
        tc.requestActive();
        tc.requestFocus();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        cityTextField = new javax.swing.JTextField();
        saveButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        cityTable = new javax.swing.JTable();

        jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        org.openide.awt.Mnemonics.setLocalizedText(jLabel2, org.openide.util.NbBundle.getMessage(CityEditorTopComponent.class, "CityEditorTopComponent.jLabel2.text")); // NOI18N

        cityTextField.setText(org.openide.util.NbBundle.getMessage(CityEditorTopComponent.class, "CityEditorTopComponent.cityTextField.text")); // NOI18N
        cityTextField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cityTextFieldActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(saveButton, org.openide.util.NbBundle.getMessage(CityEditorTopComponent.class, "CityEditorTopComponent.saveButton.text")); // NOI18N
        saveButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveButtonActionPerformed(evt);
            }
        });

        cityTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "City"
            }
        ));
        cityTable.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                cityTableKeyPressed(evt);
            }
        });
        jScrollPane1.setViewportView(cityTable);
        if (cityTable.getColumnModel().getColumnCount() > 0) {
            cityTable.getColumnModel().getColumn(0).setHeaderValue(org.openide.util.NbBundle.getMessage(CityEditorTopComponent.class, "CityEditorTopComponent.cityTable.columnModel.title0")); // NOI18N
        }

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(cityTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 201, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(saveButton))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(cityTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(saveButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 299, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void cityTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cityTextFieldActionPerformed
        if (isText(cityTextField.getText().trim())) {
            cityTextField.setBackground(Color.WHITE);
            try {
                new CitySavable().handleSave();
            } catch (IOException ex) {
                Exceptions.printStackTrace(ex);
            }
        } else {
            errorField(cityTextField);
        }
    }//GEN-LAST:event_cityTextFieldActionPerformed

    private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed
        try {
            new CitySavable().handleSave();
        } catch (IOException ex) {
            Exceptions.printStackTrace(ex);
        }   
    }//GEN-LAST:event_saveButtonActionPerformed

    private void cityTableKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_cityTableKeyPressed
        if (evt.getKeyCode() == 127) {
            City city = (City) cityTable.getValueAt(cityTable.getSelectedRow(), 0);
            if (confirm("Are you sure to delete " + city + " ?")) {
                manager.delete(City.class, city.getCity());
                fillCityTable();
            } else {
                showError("Unable to delete " + city);
            }
        }
    }//GEN-LAST:event_cityTableKeyPressed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTable cityTable;
    private javax.swing.JTextField cityTextField;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton saveButton;
    // End of variables declaration//GEN-END:variables
//    private Lookup.Result result = null;
    private UndoRedo.Manager UndoRedoManager = new UndoRedo.Manager();
    private InstanceContent instanceContent;

    @Override
    public void componentOpened() {
//        result = WindowManager.getDefault().findTopComponent("EntityExplorerTopComponent").getLookup().lookupResult(City.class);
//        result.addLookupListener(this);
//        resultChanged(new LookupEvent(result));
        fillCityTable();
        cityTextField.requestFocus();
    }

    @Override
    public void componentClosed() {
//        result.removeLookupListener(this);
//        result = null;
    }

    void writeProperties(java.util.Properties p) {
        // better to version settings since initial version as advocated at
        // http://wiki.apidesign.org/wiki/PropertyFiles
        p.setProperty("version", "1.0");
        // TODO store your settings
    }

    void readProperties(java.util.Properties p) {
        String version = p.getProperty("version");
        // TODO read your settings according to their version
    }

//    @Override
//    public void resultChanged(LookupEvent lookupEvent) {
//        Lookup.Result r = (Lookup.Result) lookupEvent.getSource();
//        Collection<City> coll = r.allInstances();
//
//        if (!coll.isEmpty()) {
//            for (City city : coll) {
//                CityEditorTopComponent tc = (CityEditorTopComponent) WindowManager.getDefault().findTopComponent("CityEditorTopComponent");
//                tc.resetFields();
//                tc.open();
//                tc.requestVisible();
////                tc.requestActive();
//                cityTextField.setText(city.getCity());
//            }
//        } else {
//            cityTextField.setText("");
//        }
//    }

    public void resetFields() {
        cityTextField.setText("");
    }

    class CitySavable extends AbstractSavable {

        String cityName;

        CitySavable() {
            register();
            this.cityName = cityTextField.getText();
        }

        @Override
        protected String findDisplayName() {
            return cityName;
        }

        @Override
        protected void handleSave() throws IOException {

            cityName = cityTextField.getText().trim();
            if (cityName.equals("")) {
                return;
            }
            NotifyDescriptor.Confirmation message = new NotifyDescriptor.Confirmation(
                    "Do you want to save \n " + cityName + "?", NotifyDescriptor.OK_CANCEL_OPTION, NotifyDescriptor.QUESTION_MESSAGE);
            Object result = DialogDisplayer.getDefault().notify(message);
//When user clicks "Yes", indicating they really want to save,
//we need to disable the Save action,
//so that it will only be usable when the next change is made.
            if (NotifyDescriptor.YES_OPTION.equals(result)) {


                //Handle the save here...
                Manager manager = Manager.getInstance();
                City city = new City(this.cityName);
                manager.update(city);
                resetFields();
                fillCityTable();
                tc().instanceContent.remove(this);
                unregister();
            }

        }

        CityEditorTopComponent tc() {
            return CityEditorTopComponent.this;
        }

        @Override
        public boolean equals(Object obj) {
            if (obj instanceof CitySavable) {
                CitySavable m = (CitySavable) obj;
                return tc() == m.tc();
            }
            return false;
        }

        @Override
        public int hashCode() {
            return tc().hashCode();
        }

    }
}
